home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 2155 < prev    next >
Encoding:
Text File  |  1996-08-06  |  1.6 KB  |  72 lines

  1. Path: newsfeed.direct.ca!usenet
  2. From: ken@direct.ca (Ken Clark)
  3. Newsgroups: comp.lang.c++
  4. Subject: Smart Pointer Implementation & question
  5. Date: 16 Jan 1996 05:46:14 GMT
  6. Organization: Internet Direct
  7. Message-ID: <4dfe36$d99@grid.direct.ca>
  8. NNTP-Posting-Host: 204.174.244.2
  9. Mime-Version: 1.0
  10. Content-Type: Text/Plain; charset=US-ASCII
  11. X-Newsreader: WinVN 0.99.6
  12.  
  13. Hi.  I have implemented a reference counting smart pointer class.  It works 
  14. well, except that I can't get a basic behavior of normal pointers: automatic 
  15. casting of subclass pointers.  Consider class shape and subclass circle.  I 
  16. can do 
  17.     shape *s;
  18.     circle *c;
  19.     ...
  20.     s = c;
  21.  
  22. What I want to be able to do (with the same semantics)
  23.     RCPtr<shape> s;
  24.     RCPtr<circle> c;
  25.     ...
  26.     s = c;
  27.  
  28. I think I understand why I can't do this (Stoustrup's square peg in round hole 
  29. analogy).  My question is, how do I get this behavior if that is what I want? 
  30.  
  31.  
  32. I have included the class below.  Any other suggestions on how to improve it 
  33. are appreciated.  Feel free to use the class in your code if you like.
  34.  
  35. Thanks,
  36.  
  37. - Ken
  38.  
  39.  
  40. template <class T>
  41. class RCPtr {
  42.     struct RCPtrRep {
  43.         T *p;
  44.         unsigned count;
  45.         RCPtrRep(T* ip = 0)    { p = ip; count = 1; }
  46.         ~RCPtrRep()        { delete p; }
  47.     } *rep;
  48. public:
  49.     RCPtr(T *ip = 0)        { rep = new RCPtrRep(ip); }
  50.     RCPtr& operator=(T *ip)
  51.     {
  52.         RCPtr::~RCPtr();
  53.         rep = new RCPtrRep(ip);
  54.         return *this;
  55.     }
  56.     RCPtr& operator=(const RCPtr& rip)
  57.     {
  58.         rip.rep->count++;
  59.         RCPtr::~RCPtr();
  60.         rep = rip.rep;
  61.         return *this;
  62.     }
  63.     ~RCPtr()
  64.     {
  65.         if (--rep->count == 0) delete rep;
  66.     }
  67.     T *operator->()            { return (T *)rep->p; }
  68.     T& operator*()            { return *(T *)rep->p; }
  69. };
  70.  
  71.  
  72.